import { v4 as uuidv4 } from 'uuid'
export const getUUID = (prefix = 'u') => {
  return `${prefix}${uuidv4()}`
}

export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function getUrlParme(parme) {
  let url = window.location.href
  //截取到参数,包含当前位置需加1,已&分割成数组。
  let parameter = url.substring(url.indexOf('?') + 1, url.length).split('&')
  //把参数放到对象里去
  // eslint-disable-next-line no-sparse-arrays
  let [value, obj] = [, {}]
  for (let i = 0; (value = parameter[i]); i++) {
    obj[value.substring(0, value.indexOf('='))] = value.substring(
      value.indexOf('=') + 1,
      value.length,
    )
  }
  //返回的值
  var returnValue = obj[parme]
  if (!returnValue) {
    return ''
  } else {
    return returnValue
  }
}

export function getFileType(url) {
  const extension = url.split('.').pop().toLowerCase()
  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension)) {
    return 'image'
  } else if (['mp3', 'wav', 'aac', 'flac', 'ogg'].includes(extension)) {
    return 'audio'
  } else if (
    ['mp4', 'mpeg', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', '3gp'].includes(
      extension,
    )
  ) {
    return 'video'
  }
  return 'unknown'
}
export function getMIME(url) {
  const type = url.split('.').pop().toLowerCase()
  let mimeMap = new Map([
    ['mp4', 'video/mp4'],
    ['mpeg', 'video/mpeg'],
    ['avi', 'video/avi'],
    ['mov', 'video/quicktime'],
    ['wmv', 'video/x-ms-wmv'],
    ['flv', 'video/x-flv'],
    ['mkv', 'video/webm'],
    ['3gp', 'video/3gpp'],
    ['mp3', 'audio/mpeg'],
    ['wav', 'audio/wav'],
    ['aac', 'audio/aac'],
    ['ogg', 'audio/ogg'],
  ])
  return mimeMap.get(type) ?? ''
}

/**
 * 计算时间差值
 * @param {Number} timeStr1
 * @param {Number} timeStr2
 * @returns
 */
export function timeDifference(timeStr1, timeStr2) {
  // 假设日期为2024年10月29日
  let date1 = new Date('2024-10-29T' + timeStr1)
  let date2 = new Date('2024-10-29T' + timeStr2)
  // 计算时间差值（毫秒）
  let diffMilliseconds = Math.abs(date2 - date1)
  // 转换成小时、分钟和秒
  let hours = Math.floor(diffMilliseconds / (1000 * 60 * 60))
  hours = hours > 9 ? hours : '0' + hours
  let minutes = Math.floor((diffMilliseconds % (1000 * 60 * 60)) / (1000 * 60))
  minutes = minutes > 9 ? minutes : '0' + minutes
  let seconds = Math.floor((diffMilliseconds % (1000 * 60)) / 1000)
  seconds = seconds > 9 ? seconds : '0' + seconds
  return {
    hours,
    minutes,
    seconds,
  }
}

export function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}
export function convertImageToBase64(url, type) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.setAttribute('crossOrigin', 'anonymous')
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0)
      const dataURL = canvas.toDataURL('image/png')
      resolve({
        dataURL,
        type,
      })
    }
    img.onerror = err => {
      reject(err)
    }
    img.src = url
  })
}
export function convertVideoToBase64(url, type) {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video')
    video.src = url
    video.setAttribute('crossOrigin', 'Anonymous') // 处理跨域
    video.setAttribute('preload', 'metadata')
    // 设置播放时间
    video.currentTime = 2
    // 当当前帧的数据已加载，但没有足够的数据来播放指定音频/视频的下一帧时触发。
    video.addEventListener('loadeddata', () => {
      const canvas = document.createElement('canvas')
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      const ctx = canvas.getContext('2d')
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
      const dataURL = canvas.toDataURL('image/png')
      resolve({
        dataURL,
        type,
      })
    })
    video.play()
    video.addEventListener('error', err => {
      reject(err)
    })
  })
}
